package com.google.android.mypetrol;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.database.Cursor;
import android.pim.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

public class HistoryList extends LinearLayout {

	private final static String TIME_FORMAT = "yyyy-MM-dd";
	
	private ListView mList;
	private Calendar mCalendar;
	private Resources mResources;
	private HistoryListAdapter mAdapter;
	
	private Spinner mYearFilter;
	private Spinner mMonthFilter;
	private Button mFilter;
	private TextView mTotalText;
	private TextView mAverageText;
	
	private int mTotalCost;

	private String mNoFilterText;

	private Cursor mCursor;
	
	private String[] mMonthList = new String[]{"1", "2", "3", "4", "5","6","7","8","9","10","11","12"};

	private ArrayList<String> mYearOptions = new ArrayList<String>();
	private ArrayList<String> mMonthOptions = new ArrayList<String>();
	
	private ArrayList<String> mTotalMonth = new ArrayList<String>();

	public HistoryList(Context context, Cursor cursor) {
		super(context);
		mResources = context.getResources();
		mCursor = cursor;


		LayoutInflater factory = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		factory.inflate(R.layout.history_list, this);
		
		mCalendar = Calendar.getInstance();
		// find all the widget
		mTotalText = (TextView)findViewById(R.id.total);
		mAverageText = (TextView)findViewById(R.id.average);
		mYearFilter = (Spinner)findViewById(R.id.year);
		mMonthFilter = (Spinner)findViewById(R.id.month);
		mFilter = (Button)findViewById(R.id.filter);
		mList = (ListView)findViewById(R.id.list);
		
		mNoFilterText = mResources.getString(R.string.history_list_all).toString();
		
		setupYearOption();
		setupMonthOption();

		mAdapter = new HistoryListAdapter(mContext,mCursor);
		mList.setAdapter(mAdapter);
		
	}

	public void updateCursor(Cursor cursor) {
		mCursor = cursor;
		mAdapter.changeCursor(mCursor);
	}
	
	public void updateListCursor() {
		mAdapter.getCursor().requery();
		setupYearOption();
	}
	
	public void setFilterClickListener (View.OnClickListener l) {
		mFilter.setOnClickListener(l);
	}
	
	public int getFilterYear() {
		return (int)mYearFilter.getSelectedView().getId();
	}
	
	public int getFilterMonth() {
		return (int)mMonthFilter.getSelectedView().getId();
	}
	
	public Cursor getCursor() {
		return mCursor;
	}
	
	public List<Integer> getSelectedItem() {
		ArrayList<Integer> list = new ArrayList<Integer>();
		int count = mList.getChildCount();
		for ( int i = 0; i < count; i ++) {
			HistoryListItem item = (HistoryListItem)mList.getChildAt(i);
			if (item.isChecked()) {
				list.add(i);
			}
		}
		return list;
	}
	
	private void setupYearOption() {
		mYearOptions.clear();
		mYearOptions.add(mNoFilterText);

		if (mCursor.moveToFirst()) {
			do {
				mCalendar.setTimeInMillis(mCursor.getLong(1));
				String year = "" + mCalendar.get(Calendar.YEAR);
				if (!mYearOptions.contains(year)) {
					mYearOptions.add(year);
				}
			} while (mCursor.moveToNext());
		}
		mYearFilter.setAdapter(new FilterAdapter(mYearOptions));
	}
	
	private void setupMonthOption() {
		mMonthOptions.clear();
		mMonthOptions.add(mNoFilterText);
		List<String> list = Arrays.asList(mMonthList);
		
		for (int i = 0; i < list.size(); i++) {
			mMonthOptions.add(list.get(i));
		}
		mMonthFilter.setAdapter(new FilterAdapter(mMonthOptions));
	}
	
	private void updateHeaderHint(){
		mTotalText.setText(mResources.getString(R.string.new_petrol_money_unit)+  mTotalCost);
		mAverageText.setText(mResources.getString(R.string.new_petrol_money_unit) + mTotalCost/mTotalMonth.size());
	}

	public void setListCallBack(AdapterView.OnItemClickListener l) {
		mList.setOnItemClickListener(l);
	}

	private String getDate(long time) {
		mCalendar.setTimeInMillis(time);
		return DateFormat.format(TIME_FORMAT, mCalendar).toString();
	}

	private String getCost(int cost) {
		return mResources.getString(R.string.history_list_total)
				+ mResources.getString(R.string.new_petrol_money_unit) + cost;
	}

	private class HistoryListAdapter extends CursorAdapter {

		public HistoryListAdapter(Context context, Cursor cursor) {
			super(context, cursor);
		}

		@Override
		public void bindView(View convertView, Context arg1, Cursor cursor) {
			HistoryListItem item = (HistoryListItem) convertView;
			item.setDate(getDate(cursor.getLong(1)));
			item.setCost(getCost(cursor.getInt(2)));
			item.setChecked(false);
			
			mTotalCost += cursor.getInt(2);
			mCalendar.setTimeInMillis(cursor.getLong(1));
			String month = mCalendar.get(Calendar.YEAR)+ "" + mCalendar.get(Calendar.MONTH);
			if (!mTotalMonth.contains(month))
				mTotalMonth.add(month);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (position == 0) {
				mTotalCost = 0;
				mTotalMonth.clear();
			}
			View v  = super.getView(position, convertView, parent);
			
			if (position == getCount() - 1) {
				updateHeaderHint();
			}
			return v;
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			View v = new HistoryListItem(mContext, getDate(cursor.getLong(1)),
					getCost(cursor.getInt(2)));
			return v;
		}

	}

	private class FilterAdapter extends BaseAdapter {
		private List<String> mOptions;

		public FilterAdapter(List<String> options) {
			mOptions = options;
		}

		public int getCount() {
			return mOptions.size();
		}

		public boolean areAllItemsSelectable() {
			return true;
		}

		public boolean isSelectable(int position) {
			return true;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			TextView text;

			if (convertView == null) {
				text = new TextView(mContext);
				text.setTextSize(15);
				text.setLayoutParams(new AbsListView.LayoutParams(
						ViewGroup.LayoutParams.FILL_PARENT, 20));
			} else {
				text = (TextView) convertView;
			}
			if (position == 0)
				text.setId(0);
			else {
				text.setId(Integer.parseInt(mOptions.get(position)));
			}
			text.setText(mOptions.get(position));
			return text;
		}
	}

}